#include <Windows.h>
#include "CTradeUpdatePacket.h"
#include "CItem.h"
#include "CGeneralItem.h"
#include "CWeaponItem.h"
#include "CArmorItem.h"
#include "CPuppetItem.h"
#include "CUsableItem.h"
#include "CLinkshellItem.h"
#include "CLinkshell.h"
#include "CConsole.h"

//used for gil
CTradeUpdatePacket::CTradeUpdatePacket(unsigned long quantity, unsigned char tradeSlotID)
{
	//CConsole::outDebOnly("Sending Gil Trade Amount: %d", quantity);
	this->type = 0x23;
	this->size = 0x14;
	memset(this->data, 0, sizeof(data));

	unsigned short itemID = 0;
	
	memcpy(this->data+0x04-0x04, &(quantity), 4);
	// 2 bytes at 0x08 unknown.  Seems to be a count of 0x23 sent
	memcpy(this->data+0x0A-0x04, &(itemID), 2);
	// 1 byte at 0x0C unknown.  Value was always 0x1D.  Tested 0x00 and 0x1D, no difference on client.
	memcpy(this->data+0x0D-0x04, &(tradeSlotID), 1);
}

CTradeUpdatePacket::CTradeUpdatePacket(CItem * item, unsigned long quantity, unsigned char tradeSlotID) {

	this->type = 0x23;
	this->size = 0x14;
	memset(this->data, 0, sizeof(data));

	unsigned short itemID = item->getId();
	char * name = item->getSignNameComp();
	
	memcpy(this->data+0x04-0x04, &(quantity), 4);
	// 2 bytes at 0x08 unknown.  Seems to be a count of 0x23 sent
	memcpy(this->data+0x0A-0x04, &(itemID), 2);
	// 1 byte at 0x0C unknown.  Value was always 0x1D.  Tested 0x00 and 0x1D, no difference on client.
	memcpy(this->data+0x0D-0x04, &(tradeSlotID), 1);

	switch(item->getType()) {
		case ITEM_NORMAL:
		case ARMOR_ENCHANTED:
		case WEAPON_ENCHANTED:
		case ARMOR_AUGMENTED:
		case WEAPON_AUGMENTED:
		case ITEM_BIGFISH:
		case ITEM_HOURGLASS:
		case ITEM_BALLISTA:
			break;
		case ITEM_LINKSHELL:
			this->itemLinkshell((CLinkshellItem*)item);
			break;
	}
}

CTradeUpdatePacket::~CTradeUpdatePacket() {

}

void CTradeUpdatePacket::itemLinkshell(CLinkshellItem * item) {
	unsigned short unknown2 = 0x4ACE;
	unsigned char lsItemState = (item->getId())-0x200;
	unsigned int lsID = item->getLinkshellId();
	if(lsID > 0) {
		CLinkshell * linkshell = CLinkshell::getLinkshellById(item->getLinkshellId());
		if(linkshell != NULL) {
			unsigned short lsColor = linkshell->getLsColor(); 
			char * lsNameComp = linkshell->getLsNameComp();
			memcpy(this->data+0x14-0x04, &lsColor, 2);
			memcpy(this->data+0x17-0x04, lsNameComp, 16);
		}
	}
	memcpy(this->data+0x0E-0x04, &lsID, 4);
	memcpy(this->data+0x12-0x04, &unknown2, 2);
	memcpy(this->data+0x16-0x04, &lsItemState, 1);
}